//
//  WBLinkWebViewController.m
//  WeiBo
//
//  Created by EDZ on 2017/10/16.
//  Copyright © 2017年 powertorque. All rights reserved.
//

#import "WBLinkWebViewController.h"

#import <WebKit/WebKit.h>

#define kTitle @"title"
#define kLoading @"loading"
#define kEstimatedProgress @"estimatedProgress"

@interface WBLinkWebViewController ()

@property (nonatomic, weak) WKWebView *webView;

@end

@implementation WBLinkWebViewController

- (void)dealloc
{
    kWBLogMothodFunc;
    [self.webView removeObserver:self forKeyPath:kTitle];
    [self.webView removeObserver:self forKeyPath:kLoading];
    [self.webView removeObserver:self forKeyPath:kEstimatedProgress];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    
    // 支持swipe前进后退手势
    webView.allowsBackForwardNavigationGestures = YES;
    
    [webView addObserver:self forKeyPath:kTitle options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:kLoading options:NSKeyValueObservingOptionNew context:nil];
    [webView addObserver:self forKeyPath:kEstimatedProgress options:NSKeyValueObservingOptionNew context:nil];
    
    [self.view addSubview:webView];
    
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.linkUrl]]];
    
    self.webView = webView;
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:kTitle]) {
        self.navigationItem.title = self.webView.title;
    }
    
    if ([keyPath isEqualToString:kLoading]) {
        if (self.webView.loading) {
            [self showProgressView];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        } else {
            [self hideProgressView];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        }
    }
    
    if ([keyPath isEqualToString:kEstimatedProgress]) {
        self.progressView.progress = self.webView.estimatedProgress;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
